package com.xnx3.banmahuishou.wangge.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.BaseVO;
import com.xnx3.DateUtil;
import com.xnx3.Lang;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.LanguageUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.weixin.applet.login.entity.WeixinAppletUserOpenid;

/**
 * 骑手管理
 * @author 王晓龙
 */
@Controller(value="BanmahuishouWanggeQishouController")
@RequestMapping("/wangge/qishou/")
public class QishouController extends BaseController {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;
	@Resource
	private SqlCacheService sqlCacheService;
	/**
	 * 骑手列表
	 */
	@RequestMapping("list${url.suffix}")
	public String list(HttpServletRequest request,Model model){
		Sql sql = new Sql(request);
		sql.setSearchColumn(new String[]{"phone","state="});
		sql.appendWhere("wangge_userid = " + getUserId());
		int count = sqlService.count("laji_qishou", sql.getWhere());
		Page page = new Page(count, 15, request);
		sql.setSelectFromAndPage("SELECT * FROM laji_qishou", page);
		sql.setDefaultOrderBy("laji_qishou.id DESC");
		List<Qishou> list = sqlService.findBySql(sql, Qishou.class);
		
		ActionLogUtil.insert(request, "骑手管理", "第"+page.getCurrentPageNumber()+"页");
		
		model.addAttribute("page", page);
		model.addAttribute("list", list);
		return "/wangge/qishou/list";
	}

	/**
	 * 新增/修改骑手
	 * @param id 要修改的id 。 如果是新增，这里传入0或者不传
	 */
	@RequestMapping("edit${url.suffix}")
	public String edit(
			@RequestParam(value = "id", required = false, defaultValue="0") int id,
			Model model, HttpServletRequest request){
		Qishou entity;
		
		if(id < 1){
			//新增
			entity = new Qishou();
			ActionLogUtil.insert(request, "进入骑手新增页面");
		}else{
			//修改
			entity = sqlService.findById(Qishou.class, id);
			if(entity == null){
				return error(model, "要修改的骑手不存在");
			}
			ActionLogUtil.insert(request, "进入修改骑手页面", entity.toString());
		}
		
		//编辑页面
		model.addAttribute("entity", entity);
		return "/wangge/qishou/edit";
	}
	
	/**
	 * 新增、修改的骑手信息进行保存
	 */
	@RequestMapping(value="save.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO variableSave(Qishou inputEntity, HttpServletRequest request){
		Qishou entity = null;			//骑手表
		//查询当前登录的后台信息
		Wangge wangge = sqlService.findById(Wangge.class, getUserId());
		User wanggeUser = sqlService.findById(User.class, getUserId());
		//查询当前后台的上级代理商后台
		User agencyUser = sqlService.findById(User.class, wangge.getDailishangUserid());
		
		if(!StringUtils.hasLength(inputEntity.getName())) {
			return error("请输入骑手姓名");
		}
		if(!StringUtils.hasLength(inputEntity.getPhone())) {
			return error("请输入手机号");
		}
		if(!StringUtils.hasLength(inputEntity.getHead())) {
			return error("请上传头像");
		}
		
		if(inputEntity.getId() == null || inputEntity.getId() < 1){
			//新增
			entity = new Qishou();
			// 判断手机号是否合法
			if(!isMobiPhoneNum(inputEntity.getPhone())) {
				return error("手机号不合法");
			}
			User user = new User();
			user.setUsername("qishou" + inputEntity.getPhone());
			user.setPassword(Lang.uuid());
			user.setNickname(inputEntity.getName());
			user.setPhone(inputEntity.getPhone());
			user.setHead(inputEntity.getHead());
			user.setAuthority("10");
			user.setRegtime(DateUtil.timeForUnix10());
			user.setAllSellWgight(0);
			user.setAllOrderNumbe(0);
			user.setAllIncomeMone(0);
			user.setMoney(0);
			user.setFreezemoney(0);
			user.setWanggeUserid(getUserId());
			user.setDailishangUserid(wangge.getDailishangUserid());
			BaseVO createUserVO = userService.createUser(user, request);
			if(createUserVO.getResult() - BaseVO.FAILURE == 0){
				return error(createUserVO.getInfo());
			}
			entity.setId(Lang.stringToInt(createUserVO.getInfo(), 0));
			ActionLogUtil.insertUpdateDatabase(request, user.getId(), "保存骑手信息", user.toString());
			//因为是新增，所以要加上新增时间
			entity.setAddtime(DateUtil.timeForUnix10());	
			entity.setAllServiceNumb(0);
			entity.setAllWgight(0);
			entity.setAllExpend(0);
			entity.setLongitude(119.14799);
			entity.setLatitude(36.711009);
			wangge.setQishouNum(wangge.getQishouNum()+1);
		}else{
			//修改
			entity = sqlService.findById(Qishou.class, inputEntity.getId());
			if(entity == null){
				return error("要修改的目标不存在");
			}
			// 修改之前先判断传入的手机号是否已有 后台 用户在使用
			if(inputEntity.getPhone() != null && inputEntity.getPhone().length() > 0){
				if(findByPhone(inputEntity.getPhone(),entity.getId()) != null){
					return BaseVO.failure(LanguageUtil.show("user_regFailureForPhoneAlreadyExist"));
				}
			}
			// 判断手机号是否合法
			if(!isMobiPhoneNum(inputEntity.getPhone())) {
				return error("手机号不合法");
			}
			User user = sqlService.findById(User.class, entity.getId());
			user.setUsername("qishou" + inputEntity.getPhone());
			user.setNickname(inputEntity.getName());
			user.setPhone(inputEntity.getPhone());
			user.setHead(inputEntity.getHead());
			sqlService.save(user);
		}
		//保存
		entity.setDailishangUserid(agencyUser.getId());
		entity.setDailishangUsername(agencyUser.getNickname());
		entity.setWanggeUserid(wanggeUser.getId());
		entity.setWanggeUsername(wanggeUser.getNickname());
		entity.setName(inputEntity.getName());
		entity.setPhone(inputEntity.getPhone());
		entity.setHead(inputEntity.getHead());
		entity.setState(Qishou.STATE_NORMAL);
		entity.setDanQuota(0);
		entity.setDayQuota(0);
		entity.setServiceArea(wangge.getServiceArea());
		
		sqlService.save(entity);
		sqlService.save(wangge);
		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "保存骑手信息", entity.toString());
		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "保存网格信息", entity.toString());
		return success();
	}
	
	/**
	 * 删除骑手信息
	 */
	@RequestMapping(value="delete.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO delete(@RequestParam(value = "id", required = false, defaultValue="0") int id, HttpServletRequest request){

		//查询当前登录网格的信息
		Wangge wangge = sqlService.findById(Wangge.class, getUserId());
		if(wangge == null){
			return error("登录信息过时,请退出重新登录");
		}
		//查询该骑手的信息
		Qishou entity = sqlService.findById(Qishou.class, id);
		if(entity == null){
			return error("要删除的目标不存在");
		}
		User user = sqlService.findById(User.class, id);
		if(user == null){
			return error("要删除的目标不存在");
		}
		sqlService.delete(entity);
		sqlService.delete(user);
		wangge.setQishouNum(wangge.getQishouNum()-1);
		sqlService.save(wangge);
		WeixinAppletUserOpenid openid = sqlService.findAloneByProperty(WeixinAppletUserOpenid.class, "userid", id);
		if (openid != null) {
			sqlService.delete(openid);
			ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "删除骑手openid", "删除骑手时,删除骑手微信绑定的openid, " + entity.toString());
			// 删除缓存中的openid
			WeixinAppletUserOpenid weixinAppletUserOpenid = sqlCacheService.findAloneByProperty(WeixinAppletUserOpenid.class, "openid", openid.getOpenid());
			if (weixinAppletUserOpenid != null) {
				sqlCacheService.deleteCacheByProperty(WeixinAppletUserOpenid.class, "openid", openid.getOpenid());
				ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "删除缓存中的openid", "删除骑手时,删除缓存中的openid, " + weixinAppletUserOpenid.toString());
			}
		}
		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "删除骑手", entity.toString());
		ActionLogUtil.insertUpdateDatabase(request, user.getId(), "删除骑手", user.toString());
		ActionLogUtil.insertUpdateDatabase(request, getUserId(), "减少当前网格一名骑手数量", wangge.toString());
		return success();
	}
	
	/**
	 * 设置工作状态
	 * @param id id编号
	 */
	@RequestMapping(value="stateEdit.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO stateEdit(HttpServletRequest request,
			@RequestParam(value = "id", required = false, defaultValue="0") int id){	
		
		Qishou qishou = sqlService.findById(Qishou.class, id);
		if(qishou == null){
			return error("要设置状态的目标不存在");
		}
		//设置请假
		if (qishou.getState() - 1 == 0) {
			qishou.setState(Qishou.STATE_LEAVE);
		}else {
			// 设置正常
			qishou.setState(Qishou.STATE_NORMAL);
		}
		sqlService.save(qishou);
		ActionLogUtil.insertUpdateDatabase(request, "正常/请假","Id为" + id + "的骑手，操作正常/请假");
		return success();
	}
}
